<?php

namespace App\Http\Controllers;

use Laravel\Lumen\Routing\Controller as BaseController;

class Controller extends BaseController
{
    /*
     * 无限极分类，获取树状数据
    */
    public function getTree ($list, $pk = 'id', $pid = 'p_id', $child = 'child', $root = 0) {
        $tree = array();
        foreach ($list as $key => $val) {
            if ($val[$pid] == $root) {
                // 获取当前$pid所有子类
                unset($list[$key]);
                if (!empty($list)) {
                    $child = $this->getTree($list, $pk, $pid, $child, $val[$pk]);
                    if (!empty($child)) {
                        $val['child'] = $child;
                    }
                }
                $tree[] = $val;
            }
        }
        return $tree;
    }

    /**
     * 中诚信接口计算签名算法
     * $data array 需要计入签名的数据
     * $privateKey string 秘钥
     */
    public function getCreditSign ($data, $privateKey) {
        ksort($data);

        // 拼装字符串
        $str = '';
        foreach ($data as $key => $value) {
            $str .= $key . $value;
        }
        
        $str .= $privateKey;

        $sign = strtoupper(md5($str));

        return $sign;
    }

    /**
     * @param $url 请求网址
     * @param bool $params 请求参数
     * @param int $ispost 请求方式
     * @param int $https https协议
     * @return bool|mixed
     */
    public static function curl($url, $params = false, $ispost = 0, $https = 0)
    {
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                if (is_array($params)) {
                    $params = http_build_query($params);
                }
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        }
        // return $url . '?' . $params;

        $response = curl_exec($ch);

        if ($response === FALSE) {
            // echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }
}
